package com.fishingwithme.infrastructure;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * Boolean 与 0/1 数值的互相转换序列化器
 */
public class BooleanNumberConverter {

    /**
     * Boolean 序列化为 0/1 的序列化器
     */
    public static class Serializer extends JsonSerializer<Boolean> {
        @Override
        public void serialize(Boolean value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            if (value == null) {
                gen.writeNull();
            } else {
                gen.writeNumber(value ? 1 : 0);
            }
        }
    }

    /**
     * 0/1 反序列化为 Boolean 的反序列化器
     */
    public static class Deserializer extends JsonDeserializer<Boolean> {
        @Override
        public Boolean deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            String value = p.getValueAsString();

            if (value == null || value.trim().isEmpty()) {
                return null;
            }

            // 处理数字类型
            if (value.matches("\\d+")) {
                int intValue = Integer.parseInt(value);
                return intValue != 0;
            }

            // 处理布尔字符串
            return Boolean.parseBoolean(value);
        }
    }
}
